#
# This is the module that includes the functions for wrapping the sketches...
#


# add_custom_target
# add_dependencies
set(ARDUINO_GENERATE_CPP_FILE ${CMAKE_CURRENT_LIST_DIR}/generate_cpp.cmake)
set(ARDUINO_FINDARDUINO_FILE ${CMAKE_CURRENT_LIST_DIR}/../FindArduino.cmake)


# generate a .cpp for sketches
# add the arduino header file for others (e.g. cpp, hpp, h, c, etc)
function(arduino_wrap_sketch output_)

  foreach(file_ ${ARGN})
    # determine file's extension
    get_filename_component( ext_ ${file_} EXT)
    string(TOUPPER "${ext_}" ext_)
    # if it's a sketch:
    if( ("${ext_}" STREQUAL ".PDE") OR ("${ext_}" STREQUAL ".INO") )

      get_filename_component( target_ ${file_} NAME)
      get_filename_component( absfile_ ${file_} ABSOLUTE)   # ensure we have the whole path
      set(dir_ ${CMAKE_CURRENT_BINARY_DIR}/${CMAKE_FILES_DIRECTORY})
      set(target_cpp_  ${dir_}/${target_}.cpp)

      add_custom_command(
        OUTPUT ${target_cpp_}
        COMMAND
          cmake
            -DARDUINO_HEADER_FILE=${ARDUINO_HEADER_FILE}
            -DIN_FILE=${absfile_}
            -DOUT_FILE=${target_cpp_}
            -P ${ARDUINO_GENERATE_CPP_FILE}
        DEPENDS
          ${file_}
          ${CMAKE_CURRENT_LIST_FILE}
          ${ARDUINO_GENERATE_CPP_FILE}
          ${ARDUINO_FINDARDUINO_FILE}
        )
      # add the built file to the out list
      set(out_ ${out_} ${target_cpp_} )
    else()
      # ensure the file gets to include the Arduino Header file
      set_source_files_properties(${file_} PROPERTIES
        COMPILE_FLAGS "-include ${ARDUINO_HEADER_FILE}"
        )
      # add this file to the list...
      set(out_ ${out_} ${file_} )
    endif()

  endforeach()
  # move the local copy to our caller's variable
  set(${output_} ${out_} PARENT_SCOPE)

endfunction()